import math
import random
from constants import *

class AI:
    def __init__(self, enemy_tank, player_tank):
        self.enemy = enemy_tank
        self.player = player_tank
        self.move_timer = 0
        self.fire_timer = 0

    def update(self):
        """更新AI行为"""
        self._update_movement()
        self._update_aiming()
        return self._try_fire()

    def _update_movement(self):
        """更新AI坦克移动"""
        self.move_timer -= 1
        if self.move_timer <= 0:
            # 随机选择新的移动方向和持续时间
            self.move_timer = random.randint(30, 120)  # 0.5到2秒
            self.move_direction = random.choice(['forward', 'backward', 'left', 'right', 'stop'])

        # 执行移动
        if self.move_direction == 'forward':
            self.enemy.move(forward=True)
        elif self.move_direction == 'backward':
            self.enemy.move(forward=False)
        elif self.move_direction == 'left':
            self.enemy.rotate(clockwise=False)
        elif self.move_direction == 'right':
            self.enemy.rotate(clockwise=True)

        # 避免与玩家坦克相撞
        self._avoid_collision()

    def _avoid_collision(self):
        """避免与玩家坦克相撞"""
        dx = self.enemy.x - self.player.x
        dy = self.enemy.y - self.player.y
        distance = math.sqrt(dx**2 + dy**2)

        if distance < AI_SAFE_DISTANCE:
            angle_to_player = math.degrees(math.atan2(-dy, dx))
            escape_angle = (angle_to_player + 180) % 360

            # 调整坦克角度，使其远离玩家
            angle_diff = (escape_angle - self.enemy.angle) % 360
            if angle_diff < 180:
                self.enemy.rotate(clockwise=True)
            else:
                self.enemy.rotate(clockwise=False)

            # 后退
            self.enemy.move(forward=False)

    def _update_aiming(self):
        """更新AI坦克瞄准"""
        dx = self.player.x - self.enemy.x
        dy = self.player.y - self.enemy.y
        angle_to_player = math.degrees(math.atan2(-dy, dx)) % 360

        # 计算炮管需要旋转的角度
        angle_diff = (angle_to_player - self.enemy.cannon_angle) % 360

        # 根据角度差选择旋转方向
        if abs(angle_diff) > 1:  # 允许1度的误差
            if angle_diff < 180:
                self.enemy.rotate_cannon(clockwise=False)
            else:
                self.enemy.rotate_cannon(clockwise=True)

    def _try_fire(self):
        """尝试发射炮弹"""
        self.fire_timer -= 1
        if self.fire_timer <= 0 and self.enemy.can_fire():
            dx = self.player.x - self.enemy.x
            dy = self.player.y - self.enemy.y
            distance = math.sqrt(dx**2 + dy**2)

            # 检查是否在射程内且炮管指向正确
            if distance <= BULLET_MAX_RANGE:
                angle_to_player = math.degrees(math.atan2(-dy, dx)) % 360
                angle_diff = abs((angle_to_player - self.enemy.cannon_angle) % 360)

                if angle_diff < 5:  # 允许5度的误差
                    self.fire_timer = random.randint(30, 90)  # 0.5到1.5秒后再次尝试发射
                    return True  # 表示可以发射

        return False  # 不发射
